<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      v-if="searchState"
    >
      <el-form-item label="商铺编号">
        <HouseInput v-model="queryParams.code"></HouseInput>
      </el-form-item>
      <el-form-item label="客户姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.zhwy_temporary_deposit_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:temporarydeposit:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      border
      v-loading="loading"
      :data="temporarydepositList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="商铺编号" align="center" prop="code" />
      <el-table-column label="客户姓名" align="center" prop="name" />
      <el-table-column label="收费项目" align="center" prop="chargeitemName" />
      <el-table-column label="收费金额" align="center" prop="money" />
      <el-table-column
        label="收款时间"
        align="center"
        prop="chargeTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.chargeTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="付款方式" align="center" prop="payName" />
      <el-table-column label="收款人姓名" align="center" prop="chargeUser" />
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.zhwy_temporary_deposit_state"
            :value="scope.row.state"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="chargeReamark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            :disabled="scope.row.state == 0 ? false : true"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:temporarydeposit:edit']"
            >退款</el-button
          >
          <el-button
            :disabled="scope.row.state == 0"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:temporarydeposit:edit']"
            >退款详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改临时收费对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item
          label="客户类型"
          prop="type"
          v-show="title != '退款' && title != '退款详情'"
        >
          <el-radio-group v-model="form.type">
            <el-radio
              @click="reset"
              v-for="dict in dict.type.zhwy_temporar_deposit_type"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="编号" prop="code" v-show="form.type == 0">
          <HouseInput
            v-model="form.code"
            v-if="title != '退款' && title != '退款详情'"
          ></HouseInput>
          <HouseInput
            v-model="form.code"
            v-else
            :isDisabled="true"
          ></HouseInput>
          <el-button
            type="primary"
            @click="searchName"
            v-show="title != '退款' && title != '退款详情'"
            >搜索</el-button
          >
        </el-form-item>
        <el-form-item label="客户姓名" prop="name" v-show="form.type == 0">
          <el-input
            v-model="form.name"
            placeholder="请输入客户姓名"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="客户姓名" prop="name" v-show="form.type == 1">
          <el-input v-model="form.name" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="收费项目" prop="chargeitemId">
          <el-select
            v-model="form.chargeitemId"
            placeholder="请选择"
            :disabled="title == '退款' || title == '退款详情'"
          >
            <el-option
              v-for="item in chargeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="付款方式" prop="payName">
          <el-select
            v-model="form.payId"
            placeholder="请选择"
            :disabled="title == '退款' || title == '退款详情'"
          >
            <el-option
              v-for="item in zhiFuList"
              :key="item.id"
              :label="item.name"
              :value="parseInt(item.id)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收费金额" prop="money">
          <el-input
            v-model="form.money"
            placeholder="请输入收费金额"
            :disabled="title == '退款' || title == '退款详情'"
          />
        </el-form-item>
        <el-form-item label="收款时间" prop="chargeTime">
          <el-date-picker
            :disabled="title == '退款' || title == '退款详情'"
            clearable
            v-model="form.chargeTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择收款时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          v-if="title == '退款' || title == '退款详情'"
          label="退款时间"
          prop="refundTime"
        >
          <el-date-picker
            :disabled="title == '退款详情'"
            clearable
            v-model="form.refundTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择退款时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="退款方式"
          prop="refundId"
          v-if="title == '退款' || title == '退款详情'"
        >
          <el-select
            v-model="form.refundId"
            placeholder="请选择"
            :disabled="title == '退款详情'"
          >
            <el-option
              v-for="item in zhiFuList"
              :key="item.id"
              :label="item.name"
              :value="parseInt(item.id)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="title == '退款' || title == '退款详情'"
          label="备注"
          prop="chargeReamark"
        >
          <el-input
            :disabled="title == '退款详情'"
            v-model="form.chargeReamark"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTemporarydeposit,
  getTemporarydeposit,
  addTemporarydeposit,
  updateTemporarydeposit,
} from "@/api/system/temporarydeposit";
import {
  listPaymentmethod,
  getPaymentmethod,
} from "@/api/system/paymentmethod";
import { listChargeitem, getChargeitem } from "@/api/charge/chargeitem";
import {
  listRentalcontract,
  getRentalcontract,
} from "@/api/rentalcontract/rentalcontract";
import { listHirer } from "@/api/renter/hirer";
import { number } from "echarts";
import { listShops, getShops } from "@/api/shops/shops";
import { getUserProfile } from "@/api/system/user";
export default {
  name: "Temporarydeposit",
  dicts: ["zhwy_temporar_deposit_type", "zhwy_temporary_deposit_state"],
  props:{
    value:{
      type: Number,
      default: null,
},
searchState:{
  type:Boolean,
  default:true
}
  },
  watch:{
    value:{
      immediate:true,
      handler(val){
        this.queryParams.shopsId = val
        this.getList()
      }
    },
    searchState:{
      immediate:true,
      handler(val){
        if(val){
          this.getList()
        }
      }
    }
  },
  data() {
    return {
      // 用户信息
      userInfo: {
        chargeUser: null,
        refundUser: null,
      },
      // 租售合同列表
      customerList: [],
      // 收费项目
      chargeList: [],
      // 支付方式
      zhiFuList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 临时收费表格数据
      temporarydepositList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        code: null,
        pageNum: 1,
        pageSize: 10,
        id: null,
        shopsId: null,
        name: null,
        state: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [{ required: true, message: "编号不能为空", trigger: "change" }],
        type: [
          { required: true, message: "客户类型不能为空", trigger: "change" },
        ],
        shopsId: [
          { required: true, message: "商铺编号不能为空", trigger: "change" },
        ],
        name: [
          { required: true, message: "请输入编号后点击搜索", trigger: "blur" },
        ],
        chargeitemId: [
          { required: true, message: "收费项目不能为空", trigger: "change" },
        ],
        money: [
          { required: true, message: "收费金额不能为空", trigger: "blur" },
        ],
        chargeTime: [
          { required: true, message: "收款时间不能为空", trigger: "blur" },
        ],
        payId: [
          { required: true, message: "付款方式不能为空", trigger: "change" },
        ],
        refundTime: [
          { required: true, message: "退款时间不能为空", trigger: "change" },
        ],
        refundId: [
          { required: true, message: "退款方式不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getZhiFuList();
    this.getChargeList();
    this.reset();
    this.getUserInfo();
  },
  methods: {
    // 获取当前登录用户
    getUserInfo() {
      getUserProfile().then((resp) => {
        console.log(resp);
        this.userInfo.chargeUser = resp.data.nickName;
        this.userInfo.refundUser = resp.data.nickName;
        console.log(this.userInfo);
      });
    },
    // // 收费项查询
    // getChargeById(list){
    //   for(let item of list){
    //     getChargeitem(item.chargeitemId).then(res=>{
    //       if(res.code == 200){
    //         item.chargeitemName = res.data.name
    //       }
    //     })
    //   }
    //   return list;
    // },
    // 搜索客户姓名
    searchName() {
      listShops({ code: this.form.code }).then((res) => {
        if (res.code == 200) {
          this.form.shopsId = res.rows[0].id;
          listRentalcontract({ shopsId: this.form.shopsId }).then((res) => {
            if (res.code == 200) {
              listHirer({ id: res.rows[0].hirerId }).then((res) => {
                if (res.code == 200) {
                  this.form.name = res.rows[0].name;
                } else {
                  this.$message.error(res.msg);
                }
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    // 获取收费项目
    getChargeList() {
      listChargeitem({}).then((res) => {
        this.chargeList = res.rows;
      });
    },
    // 获取支付方式列表
    getZhiFuList() {
      listPaymentmethod({}).then((response) => {
        this.zhiFuList = response.rows;
      });
    },

    getList() {
      this.loading = true;

      listTemporarydeposit(this.queryParams).then((response) => {
        // 创建一个 Promise 数组，用于同时处理支付方式和收费项目的调用
        if(response.code == 200){
          this.temporarydepositList = response.rows;
          this.loading = false
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: 0,
        shopsId: null,
        name: null,
        chargeitemId: null,
        money: null,
        chargeTime: null,
        payId: null,
        chargeUser: null,
        refundUser: null,
        refundTime: null,
        refundId: null,
        state: null,
        chargeReamark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.code != null && this.queryParams.code != "") {
        listShops({ code: this.queryParams.code }).then((res) => {
          if (res.code == 200) {
            this.queryParams.shopsId = res.rows[0].id;
            this.getList();
          }
        });
      } else {
        this.getList();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this. queryParams={
        code: null,
        pageNum: 1,
        pageSize: 10,
        id: null,
        shopsId: null,
        name: null,
        state: null,
      },
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 添加按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新建临时收费";
    },
    /** 退款按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getTemporarydeposit(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "退款";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.title == "退款") {
            this.form.refundUser = this.userInfo.refundUser;
            this.form.state = 1;
            updateTemporarydeposit(this.form).then((response) => {
              this.$modal.msgSuccess("退款成功!");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.chargeUser = this.userInfo.chargeUser;
            listShops({ code: this.form.code }).then((res) => {
              if (res.code == 200) {
                this.form.shopsId = res.rows[0].id;
                addTemporarydeposit(this.form).then((response) => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            });
          }
        }
      });
    },
    /** 退款详情按钮操作 */
    handleDelete(row) {
      this.reset();
      const id = row.id;
      getTemporarydeposit(id).then((res) => {
        this.form = res.data;
        this.open = true;
        this.title = "退款详情";
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/temporarydeposit/export",
        {
          ...this.queryParams,
        },
        `temporarydeposit_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
